package cn.thoughtworks.school.programCenter.configrations;

import cn.thoughtworks.school.programCenter.entities.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

public class ProgramDesignInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String uri = request.getServletPath();
        if (needToInterceptUrl(uri)) {
            String token = getTokenHeader(request);
            User user = TokenUtil.parseTokenToJsonObject(token);
            if (isProgramDesignRole(user, uri)) {
                return true;
            }
            httpServletResponse.setStatus(403);
            return false;
        }

        return true;
    }

    private boolean needToInterceptUrl(String uri) {
        return programDesignInterface().stream().anyMatch(uri::matches);
    }

    private String getTokenHeader(HttpServletRequest request) {
        return request.getHeader("token");
    }

    private boolean isProgramDesignRole(User user, String uri) {
        return programDesignInterface().stream().anyMatch(uri::matches) && user.getRoles().contains(7);
    }

    private List<String> programDesignInterface() {
        String programs = "/api/programs";
        String workspace = "/api/programs/workspace";
        String subTopics = "/api/programs/subTopics";
        String topicTask = "/api/programs/\\d+/topicTask";
        String quizzes = "/api/v2/assignments/quizzes";
        String assignmentsById = "api/v2/assignments/\\d+";
        String quizzesByIds = "/api/v2/assignments/quizzesByIds";
        String[] array = {programs,workspace,subTopics,topicTask,quizzes,assignmentsById,quizzesByIds};
        return Arrays.asList(array);
    }
}
